package com.globant.dashboard.webapp.controllers;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.globant.dashboard.model.Language;
import com.globant.dashboard.model.User;
import com.globant.dashboard.service.UserService;

@Controller
public class AdminController {
	
	@Autowired
	private UserService userService;
	
	@RequestMapping(value="/admin/main.do", method=RequestMethod.GET)
	public String adminMain(Model model){
		Object principal = SecurityContextHolder.getContext()
				.getAuthentication().getPrincipal();
		UserDetails userDetails = null;
		// if (principal instanceof UserDetails) {
			userDetails = (UserDetails) principal;
		// }
		String email = userDetails.getUsername();
		User user = userService.getUserByEmail(email);

		final String currentUser = user.getName();
		//String message = "";

		model.addAttribute("username", currentUser);
		//model.addAttribute("message", message);
		
		return "adminMain";
	}
	
	@RequestMapping(value="/admin/dashboard.do", method=RequestMethod.GET)
	public String adminDashboard(Model model){
		int countResult = userService.countUsers();
		List<User> list = userService.getAllUsers(1,20);
		
		int pages = ((countResult-1)/20)+1;
		List<Integer> pagesList = new ArrayList<Integer>();
		for(int i=0; i<pages; i++){
			pagesList.add(i+1);
		}
		//Busco el mail del usuario logeado
		Object principal = SecurityContextHolder.getContext()
				.getAuthentication().getPrincipal();
		UserDetails userDetails = null;
		userDetails = (UserDetails) principal;
		String email = userDetails.getUsername();
		
		model.addAttribute("usersList",list);
		model.addAttribute("countResult", countResult);
		model.addAttribute("pagesList", pagesList);
		model.addAttribute("page2Display", 1);
		model.addAttribute("loggedUser", email);
		
		return "dashboard";
	}
	
	@RequestMapping(value="/admin/searchUsers.do", method=RequestMethod.GET)
	public String adminSearchUsers(Model model, String search, int pageNumber){
		pageNumber = pageNumber<=0 ? 1 : pageNumber; 
		int countResult = userService.countUsersByCriteria(search);
		
		int pages = ((countResult-1)/20)+1;
		List<Integer> pagesList = new ArrayList<Integer>();
		for(int i=0; i<pages; i++){
			pagesList.add(i+1);
		}
		
		List<User> list = userService.getByCriteria(search,pageNumber,20);
		
		//Busco el mail del usuario logeado
		Object principal = SecurityContextHolder.getContext()
				.getAuthentication().getPrincipal();
		UserDetails userDetails = null;
		userDetails = (UserDetails) principal;
		String email = userDetails.getUsername();
		
		
		model.addAttribute("usersList", list);
		model.addAttribute("search", search);
		model.addAttribute("countResult", countResult);
		model.addAttribute("pagesList", pagesList);
		model.addAttribute("page2Display", pageNumber);
		model.addAttribute("loggedUser", email);
		return "dashboard";
	}
	
	@RequestMapping(value="/admin/editUser.do", method=RequestMethod.GET)
	public String adminEditUser(int id, Model model){
		User user = userService.getUserById(id);
		model.addAttribute("user", user);
		
		model.addAttribute("availableLanguages", Language.getAvailableLanguages());
		model.addAttribute("action", "editUser");
		
		return "updateProfile";
	}
	
	@RequestMapping(value="/admin/update.do", method=RequestMethod.POST)
	public String adminEditUser(User user, Model model, HttpServletRequest request){
		String action = request.getParameter("editWho");
		if("editMyProfile".equals(action)){
			String url = adminEditProfile(user,model,request);
			return url;
		}
		try{
			userService.updateUser(user);
		}catch(Exception e){
			String errorMsg = e.getMessage();
			model.addAttribute("user", user);
			model.addAttribute("availableLanguages", Language.getAvailableLanguages());
			model.addAttribute("errorMsg", errorMsg);
			return "updateProfile";
		}
		return "redirect:/admin/dashboard.do"; 
	}
	
	public String adminEditProfile(User user, Model model,HttpServletRequest request){
		try {
			userService.updateUser(user);
			if(!user.getEmail().equals(request.getParameter("emailModified"))) {
				SecurityContextHolder.getContext().getAuthentication().setAuthenticated(false);
			}
			//model.addAttribute("successMsg", "The profile has been upadated.");
		} catch (Exception e) {
			model.addAttribute("user", user);
			model.addAttribute("availableLanguages", Language.getAvailableLanguages());
			model.addAttribute("errorMsg", e.getMessage());
			return "updateMyProfile";
		}

		return "redirect:/admin/main.do";
	}
	
	@RequestMapping(value="/admin/delete.do", method=RequestMethod.POST)
	public String adminDeleteUser(Model model, HttpServletRequest request){
		String[] usersId = request.getParameterValues("usersId");
		String errorMsg = "Could not delete these users:";
		boolean error = false;
		if(usersId!=null){
			//
			for(int i=0; i<usersId.length; i++){
				User user = new User();
				user.setId(Integer.parseInt(usersId[i]));
				try{
					userService.deleteUser(user);
				}catch(Exception e){
					e.printStackTrace();
					errorMsg = errorMsg +" *"+ user.getId();
					error = true;
				}
			}
			
			//Setting messages
			if(error){
				model.addAttribute("errorMsg", errorMsg);
			}else{
				model.addAttribute("successMsg", "You have correctly deleted "+usersId.length+" users.");
			}
			return "deletedUser";
			
		}else{
			//No users to delete. Go back to Dashboard. 
			System.out.println("No user selected.");
			return "redirect:/admin/dashboard.do";
		}
	}
	
	@RequestMapping(value="/admin/create.do", method=RequestMethod.GET)
	public String adminDisplayCreateUser(Model model){
		model.addAttribute("availableLanguages", Language.getAvailableLanguages());
		return "newUser";
	}
	
	@RequestMapping(value="/admin/create.do", method=RequestMethod.POST)
	public String adminCreateUser(User user, Model model){
		System.out.println(user.getAccessType().getRole());
		try{
			user.setEnabled(true);
			userService.insertUser(user);
		} catch(Exception e){
			String errorMsg = e.getMessage();
			model.addAttribute("errorMsg", errorMsg);
			model.addAttribute("availableLanguages", Language.getAvailableLanguages());
			return "newUser";
		}
		
		return "redirect:/admin/dashboard.do";
		
	}
	@RequestMapping(value = "/admin/editMyProfile.do", method = RequestMethod.GET)
	public String updateUser(Model model) {

		Object principal = SecurityContextHolder.getContext()
				.getAuthentication().getPrincipal();
		UserDetails userDetails = null;
		userDetails = (UserDetails) principal;
		String email = userDetails.getUsername();
		User user = userService.getUserByEmail(email);

		model.addAttribute(user);
		model.addAttribute("availableLanguages", Language.getAvailableLanguages());
		model.addAttribute("action", "editMyProfile");
		
		return "updateProfile";
	}

}
